package com.rtu.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.rtu.dao.IRainGatherDataDao;
import com.rtu.dao.IStationDao;
import com.rtu.domain.Station;
import com.rtu.dto.QueryStationDto;
import com.rtu.dto.StationResponse;
import com.rtu.service.IStationService;

@Service
public class StationServiceImpl implements IStationService{
	
	@Resource
	private IStationDao stationDao;
	@Resource
	private IRainGatherDataDao rainGatherDataDao;

	@Override
	public Map query(QueryStationDto dto) {
        Map map = new HashedMap();
        List<StationResponse> list = new ArrayList<StationResponse>();
        Integer count = stationDao.count();
        if (count == 0) {
            map.put("totalPage",0);
            map.put("totalCount",0);
        } else {
            int totalPage = (count % dto.getPageRowCount() == 0) ? count / dto.getPageRowCount() : count / dto.getPageRowCount() + 1;
            dto.setStart((dto.getPage() - 1) * dto.getPageRowCount());
            list = stationDao.query(dto);
            for(StationResponse r : list) {
            	if(StringUtils.isNotBlank(r.getCalculationFormula())) {
                	Station station = new Station();
                	station.setCalculationFormula(r.getCalculationFormula());
                	station.setId(r.getId());
                	r.setCurrentWaterLevel(rainGatherDataDao.queryData(station));
            	}
            }
            map.put("totalPage",totalPage);
            map.put("totalCount",count);
        }
        map.put("pageRowCount", dto.getPageRowCount());
        map.put("page",dto.getPage());
        map.put("list",list);
        return map;
	}

	@Override
	public Map queryStationById(int id) {
		Map map = new HashedMap();
		Station station = stationDao.queryById(id);
		map.put("station", station);
		return map;
	}

	@Override
	public int updateStation(Station station) {
		return stationDao.updateStation(station);
	}

	@Override
	public int insertStation(Station station) {
		return stationDao.insertStation(station);
	}

}
